package org.s45.erp.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ttxs.common.core.utils.ServletUtils;
import com.ttxs.common.security.properties.IgnoreWhiteProperties;
import com.ttxs.common.security.properties.TokenProperties;
import com.ttxs.common.security.util.AuthUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private IgnoreWhiteProperties ignoreWhiteProperties;
    @Autowired
    private TokenProperties tokenProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();

        log.info("uri:{}", path);
        log.info("whites:{}", ignoreWhiteProperties.getWhites());

        if(AuthUtils.isMatch(ignoreWhiteProperties.getWhites(), path)) {
            return chain.filter(exchange);
        }
        String token = getToken(request);
        if(!StringUtils.hasText(token)) {
            return error(response, HttpStatus.UNAUTHORIZED, "令牌不能为空");
        }
        if (!AuthUtils.isLogin(token)) {
            return error(response, HttpStatus.UNAUTHORIZED, "用户未登录");
        }
        String funcName = getFuncName(request);

        if (!StringUtils.hasText(funcName)) {
            return error(response, HttpStatus.UNAUTHORIZED, "请通过客户端访问");
        }
        if (!hasPerms(funcName, token)) {
            return error(response, HttpStatus.FORBIDDEN, "无权访问此功能");
        }
        return chain.filter(exchange);
    }

    private boolean hasPerms(String funcName, String token) {
        Set<String> funcList = (Set<String>) AuthUtils.getLoginUser(token).getExtra();
        if (log.isInfoEnabled()) {
            log.debug("funcName:{}, funcList:{}", funcName, funcList);
        }
        return funcList.contains(funcName);
    }

    @SneakyThrows
    private String getFuncName(ServerHttpRequest request) {
        String funcName = request.getHeaders().getFirst("funcName");
        return URLDecoder.decode(funcName, "UTF-8");
    }

    @SneakyThrows
    private Mono<Void> error(ServerHttpResponse response, HttpStatus status, String msg) {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> data = new HashMap<>();
        data.put("code", status.value());
        data.put("msg", msg);
        String json = objectMapper.writeValueAsString(data);
        return ServletUtils.webFluxResponseWriter(response, status, json);
    }

    private String getToken(ServerHttpRequest request) {
        return request.getHeaders().getFirst(tokenProperties.getName());
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
